package com.service.totalauth.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.service.config.constant.ApiUrlConstants;
import com.service.config.utils.IdUtil;
import com.service.config.utils.JsonXMLUtils;
import com.service.config.utils.RedisUtil;
import com.service.config.utils.Result;
import com.service.totalauth.dao.AuthorizationUserDao;
import com.service.totalauth.dao.ProgrammeApiBindDao;
import com.service.totalauth.dto.AuthorizationDto;
import com.service.totalauth.entity.Authorization;
import com.service.totalauth.entity.AuthorizationUser;
import com.service.totalauth.entity.PortalUser;
import com.service.totalauth.entity.ProgrammeApiBind;
import com.service.totalauth.service.PortalUserService;
import com.service.totalauth.service.ThirdAuthorizationService;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

import static com.service.config.constant.ApiUrlConstants.URL_FIRST;
import static com.service.config.constant.Constant.*;
import static com.service.config.utils.DesUtil.decodeUrlToString;

/**
 * @author ：hjl
 * @date ：Created in 2021/12/08 10:48
 * @description：
 */
@Service
@Slf4j
public class ThirdAuthorizationServiceImpl implements ThirdAuthorizationService {
    private static final Logger LOG = LoggerFactory.getLogger(AuthorizationUserServiceImpl.class);

    @Resource
    private RedisUtil redisUtil;
    @Resource
    private PortalUserService portalUserService;
    @Resource
    private AuthorizationUserDao authorizationUserDao;
    @Resource
    RestTemplate restTemplate;
    @Resource
    private ProgrammeApiBindDao programmeApiBindDao;
    @Resource
    private CloudCampusApi cloudCampusApi;

    /**
     * 第三方授权终端用户
     * @param authorizationVo
     * @throws Exception
     * @return
     */
    @Override
    @Transactional
    public Result setAuthorization(AuthorizationDto authorizationVo,Integer type) throws Exception {
        if (authorizationVo.getProgrammeInfoBindId() == null) {
            return Result.failure(PARAMETER_NOT_FOUND,parameterNotFound); // 参数错误
        }
        ProgrammeApiBind programmeApiBind = programmeApiBindDao.queryById(authorizationVo.getProgrammeInfoBindId());
        if(null==programmeApiBind)
        {
            return Result.failure("参数错误");
        }
        PortalUser portalUser = portalUserService.queryById(programmeApiBind.getPortalUserId());
        if (null==portalUser)
        {
            return Result.failure(AUTH_FLAIRE,AUTH_FLAIRE_DESC); //认证失败
        }
        String auth = auth(portalUser.getTenantName(), portalUser.getTenantPwd(), portalUser.getDomain(), authorizationVo);// 认证授权
        if (auth == null) {
            return Result.failure(AUTH_FLAIRE,AUTH_FLAIRE_DESC); //认证失败
        }
        insertAuthorizationUser(authorizationVo, IdUtil.getStringId(), auth); // 插入认证信息
        return Result.ok();
    }

    /**
     * 授权终端
     * @param username
     * @param password
     * @param domain
     * @param authorizationVo
     * @return
     * @throws Exception
     */
    private String auth(String username,String password,String domain,AuthorizationDto authorizationVo) throws Exception {
        HttpHeaders requestHeaders = getHttpHeaders();
        HttpHeaders token = cloudCampusApi.getTokenRedis(username, password, domain, requestHeaders);
        if (token == null) {
            return null;
        }
        authorizationVo.setUserName(username);
        return setAuthorizationUser(token, domain, authorizationVo);
    }

    private HttpHeaders getHttpHeaders() {
        HttpHeaders requestHeaders = new HttpHeaders();
        MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8");
        requestHeaders.setContentType(type);
        requestHeaders.add("Accept", MediaType.APPLICATION_JSON.toString());
        return requestHeaders;
    }

    /**
     * 授权终端用户
     * @param requestHeaders
     * @param authorizationVo
     * @return
     * @throws Exception
     */

    private String setAuthorizationUser(HttpHeaders requestHeaders,String domain, AuthorizationDto authorizationVo) throws Exception {
        try {
            Map map = new HashMap();
            Authorization authorizationUser = new Authorization();
            authorizationUser.setDeviceMac(authorizationVo.getApmac());
            String ssid = authorizationVo.getSsid();
            for (int i = 0 ;i< 20; i++) {
                ssid = decodeUrlToString(ssid);
            }
            if (ssid.contains(" ")) {
                ssid = ssid.replaceAll(" ","+");
            }
            authorizationUser.setSsid(ssid);
            authorizationUser.setTerminalIpV4(authorizationVo.getUaddress());
            if (authorizationVo.getNodeIp() != null) {
                authorizationUser.setNodeIp(authorizationVo.getNodeIp());
            }
            authorizationUser.setTerminalMac(authorizationVo.getUmac());
            if (authorizationVo.getUserName() != null && !"".equals(authorizationVo.getUserName())) {
                authorizationUser.setUserName(authorizationVo.getUserName());
            }
            map = JSONObject.parseObject(JsonXMLUtils.obj2json(authorizationUser));
            HttpEntity<Map> requestEntity = new HttpEntity<Map>(map, requestHeaders);
            ResponseEntity<JSONObject> response = restTemplate.postForEntity(URL_FIRST.concat(domain).concat(ApiUrlConstants.AUTHORIZATION_URL_NOT), requestEntity, JSONObject.class);
            JSONObject jsonObject = response.getBody();
            LOG.info("jsonObject : "+ jsonObject);
            return jsonObject.getString("psessionid");
        }catch (Exception e) {
            LOG.error(e.getMessage());
            return null;
        }
    }

    /**
     * @param authorizationVo
     * @param id
     * @param response
     * @return
     */
    private AuthorizationUser insertAuthorizationUser(AuthorizationDto authorizationVo, String id, String response) {
        AuthorizationUser authorizationUser =new AuthorizationUser();
        authorizationUser.setId(id);
        authorizationUser.setApMac(authorizationVo.getApmac());
        authorizationUser.setNodeIp(authorizationVo.getNodeIp());
        authorizationUser.setPsessionId(response);
        authorizationUser.setSsid(authorizationVo.getSsid());
        authorizationUser.setStatus("0");
        authorizationUser.setTerminalIpV4(authorizationVo.getUaddress());
        authorizationUser.setTerminalMac(authorizationVo.getUmac());
        if (authorizationVo.getUserName() != null && !"".equals(authorizationVo.getUserName())) {
            authorizationUser.setUserName(authorizationVo.getUserName());
        }
        authorizationUserDao.insert(authorizationUser);
        return authorizationUser;

    }
}
